<script>
function Promise(executor){
    this.status = 'pending'
    this.value = null
    this.reason = null
    this.onFulfilledFunc = []
    this.onRejectedFunc = []

    const resolve = value => {
        if(this.status === 'pending'){
            this.value = value
            this.status = 'fulfilled'
            this.onFulfilledFunc.forEach(func => {
                func(this.reason)
            })
        }
    }
    const reject = reason => {
        if(this.status === 'pending'){
            this.reason = reason
            this.status = 'rejected'
            this.onRejectedFunc.forEach(func => {
                func(this.value)
            })
        }
    }
    executor(resolve, reject)
}

Promise.prototype.then = function(onfulfilled, onrejected){
    onfulfilled = typeof onfulfilled === 'function' ? onfulfilled : data => data
    onrejected = typeof onrejected === 'function' ? onrejected : err => {throw err}
    if(this.status === 'fulfilled'){
        onfulfilled(this.value)
    }
    if(this.status === 'rejected'){
        onrejected(this.reason)
    }
    if(this.status === 'pending'){
        this.onFulfilledFunc.push(onfulfilled)
        this.onRejectedFunc.push(onrejected)
    }
}

</script>